﻿/*----------------------------------------------------------------
//  <copyright file="DbContextModelCache.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2023-12-06 10:56</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Entity.Internal
{
    #region "上下文数据模型缓存"
    /// <summary>
    /// 上下文数据模型缓存
    /// </summary>
    internal class DbContextModelCache
    {
        //字段
        private readonly ConcurrentDictionary<Type, IModel> _dict = new();
        private readonly ILogger _logger;

        #region "构造函数"
        #region "初始化一个 <see cref="DbContextModelCache"/> 类型的新实例"
        /// <summary>
        /// 初始化一个 <see cref="DbContextModelCache"/> 类型的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public DbContextModelCache(IServiceProvider provider)
        {
            _logger = provider.GetLogger(GetType());
        }
        #endregion

        #endregion

        #region "方法"
        #region "获取指定上下文类型的模型"
        /// <summary>
        /// 获取指定上下文类型的模型
        /// </summary>
        /// <param name="dbContextType">上下文类型</param>
        /// <returns>数据模型</returns>
        public IModel Get(Type dbContextType)
        {
            IModel model = _dict.GetOrDefault(dbContextType);
            _logger.LogDebug("从 上下文模型缓存(DbContextModelCache) 中获取数据上下文 {dbContextType} 的Model缓存，结果：{result}。", dbContextType, model != null);
            return model;
        }
        #endregion
        #region "设置指定上下文类型的模型"
        /// <summary>
        /// 设置指定上下文类型的模型
        /// </summary>
        /// <param name="dbContextType">上下文类型</param>
        /// <param name="model">模型</param>
        public void Set(Type dbContextType, IModel model)
        {
            _logger.LogDebug("在 上下文模型缓存(DbContextModelCache) 中存入数据上下文 {dbContextType} 的Model缓存", dbContextType);
            _dict[dbContextType] = model;
        }
        #endregion
        #region "移除指定上下文类型的模型"
        /// <summary>
        /// 移除指定上下文类型的模型
        /// </summary>
        /// <param name="dbContextType"></param>
        public void Remove(Type dbContextType)
        {
            _logger.LogDebug("从 上下文模型缓存(DbContextModelCache) 中移除数据上下文 {dbContextType} 的Model缓存", dbContextType);
            _dict.TryRemove(dbContextType, out IModel _);
        }
        #endregion

        #endregion

    }
    #endregion

}
